<template>
  <page-wrap :showTop="false" hide-tab back title="我的权益">
    <scroll-view
      class="my-rights-v2"
      scroll-y="false"
      @scroll="handleScrollToTop"
      :scroll-top="scrollTop"
    >
      <view class="basic-info">
        <view class="info-card">
          <view
            :class="[
              isProfessional ? 'current-levle' : 'current-levle-consultant'
            ]"
          ></view>
          <view
            :class="[isProfessional ? 'rights-logo' : 'rights-logo-consultant']"
          ></view>
          <view class="person-info">
            <image class="avatar" :src="userInfo.pic || defaultAvatar"></image>
            <view class="version-name">
              <view
                class="version"
                :style="{ color: isProfessional ? '#50BC5A' : '#5F65FF' }"
              >
                {{ isProfessional ? '专业版' : '顾问版' }}</view
              >
              <view class="name">{{ userInfo.personName }}</view>
            </view>
          </view>
          <view class="dead-line">{{ deadline }}到期</view>
        </view>
      </view>

      <view :class="['rights-list']">
        <view class="rights-title">
          <view
            class="color-title"
            :style="{
              backgroundColor: isProfessional ? '#50BC5A' : '#5F65FF'
            }"
          ></view>
          <view class="rights-name">权益</view>
          <view class="notify" v-if="!isProfessional"
            >（提示：任选 <span>3</span> 个工具去咨询顾问解析）</view
          >
        </view>
        <scroll-view class="rights-content" scroll-y="true">
          <view
            class="rights-item"
            v-for="(item, index) in mymyOrderRights"
            :key="index"
            :style="{
              border: index === mymyOrderRights.length - 1 ? 'none' : ''
            }"
          >
            <view class="first-line">{{ item.rightName }}</view>
            <view
              class="second-line"
              v-for="(_item, _index) in item.children"
              :key="_index"
              @click="handleShowDesc(item, index, _item)"
            >
              <template v-if="_item.rightStatus != 4">
                <view class="current-type">{{ _item.rightName }}</view>
                <view
                  class="current-step"
                  :style="{ color: isProfessional ? '#50bc5a' : '#7A7FFF' }"
                  ><span
                    >{{ _item.userNum ? _item.userNum : 0 }}/{{
                      _item.rightCount ? _item.rightCount : 1
                    }}</span
                  >{{
                    (_item.rightId === 15 || _item.rightId === 22) &&
                    _item.extra == null
                      ? '未解析'
                      : _item.rightStatus === 2
                      ? '去查看'
                      : '去完成' + '   '
                  }}
                  <view
                    :class="[
                      _item.rightId === 15 && _item.extra == null
                        ? 'no-arrow'
                        : 'green-arrow'
                    ]"
                  ></view>
                </view>
              </template>
            </view>
          </view>
        </scroll-view>
        <view class="bottom">已经到底啦~</view>
      </view>
    </scroll-view>
  </page-wrap>
</template>

<script>
import {
  myOrderRights,
  ztBurryPoint,
  getUserInfo,
  getMyRankingInfo,
  getPersonRightNum
} from '@/api/modules/career';
import common from '@/api/common.js';

import { env } from '@/api/root';
export default {
  components: {},
  data() {
    return {
      personId: '',
      mymyOrderRights: [], // 权益树
      isProfessional: true, // 判断是true专业版还是false顾问版
      deadline: '2023.01.02', // 到期时间
      defaultAvatar: this.$imgBase + 'careerPath/fakeAvatar2nd.png',
      currentScrollTop: 0, // 表示当前的scrollTop的值来判断显示完整的资料卡还是一个小横条
      scrollTop: 0,
      userInfo: {
        pic: '',
        personName: 'aaa'
      }, // 个人信息包含头像和名字
      assessmentVersion: uni.getStorageSync('assessmentVersion')
    };
  },
  onShow() {
    this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
    this.getUserInfoFn();
    this.myOrderRights();
  },
  mounted() {
    this.myOrderRights();
  },
  methods: {
    async getPersonRightNumFn(rightId) {
      const params = {
        personId: this.personId || undefined,
        rightId,
        cardType: this.info.cardType
      };
      const res = await getPersonRightNum(params);
      return res.data.ownNum - res.data.useNum;
    },
    async handleShowDesc(item, index, _item) {
      console.log('_item.rightId', _item.rightId);
      if (!this.personId) {
        // this.showLoginDialog();
        return;
      }
      // if (!this.info.personName) {
      //   uni.showToast({ icon: "none", title: "请先激活！" });
      //   return;
      // }
      // 如果是children的长度<2,不显示子项目，而是直接去测试或者查看结果
      if (item.children.length < 2) {
        // 同一处理还没开放的情况
        if (item.children[0].rightStatus == 0) {
          uni.showToast({ icon: 'none', title: '敬请期待！' });
          return;
        }
        // 职业测评
        if (item.rightId == 10) {
          this.reqZtBurryPoint(item.children[0]);
          if (item.children[0].rightStatus == 1) {
            uni.navigateTo({
              url: `/pagesSub/career/activity/vocationalAssessment?personId=${this.personId}`
            });
          } else {
            uni.navigateTo({
              url: `/pagesSub/careerAssessResultActNew/index?personId=${this.personId}`
            });
            // if (!this.assessmentVersion || this.assessmentVersion == '1') {
            //   uni.navigateTo({
            //     url: `/pagesSub/career/activity/CareerAssessResultAct?personId=${this.personId}`
            //   });
            // } else if (this.assessmentVersion == '2') {
            //   uni.navigateTo({
            //     url: `/pagesSub/careerAssessResultActNew/index?personId=${this.personId}`
            //   });
            // }
          }
        }
        // AI面评
        if (item.rightId == 16) {
          let array = this.mymyOrderRights;
          const targetItem = array.find((item) => item.rightId == 10);
          // if (targetItem.children[0].rightStatus == 1) {
          //   uni.showToast({ icon: "none", title: "请先完成职业测评" });
          // } else {
          let child = item.children[0];
          const queryParams = {
            userNum: child.userNum || 0,
            rightCount: child.rightCount || 3
          };
          const queryString = common.serializeQueryParams(queryParams);
          uni.navigateTo({
            url: `/pagesSub/companyCenter/interviewAI/majorSearchAI${queryString}`
          });
          // }
        }
        // 职业报告
        if (item.rightId == 12) {
          console.log('item', item);
          // if (this.mymyOrderRights[index - 1].children[0].rightStatus == 1) {
          //   uni.showToast({ icon: "none", title: "请先完成职业测评！" });
          //   return;
          // }
          this.reqZtBurryPoint(item.children[0]);

          uni.navigateTo({
            url: `/pagesSub/careerNew/selectCareerReport/index?rightId=${9}&rightCount=${
              item.children[0] && item.children[0].rightCount
            }&rightPersonId=${this.personId}`
          });
        }
        // 性格测评
        if (item.rightId == 14) {
          const discLeftUseNum = await this.getPersonRightNumFn(1); // 性格测评的内层rightId是1
          if (item.children[0].rightStatus == 1) {
            const { personId, personName } = this.info;
            let url;
            if (env == 'test') {
              url = `https://3gtest.crm1001.com/disc/#/disc/question?personId=${personId}&iname=${personName}&phone=18825449087&from=careerPathResult&discLeftUseNum=${discLeftUseNum}&cardType=${this.info.cardType}`;
            } else if (env == 'pro' || env == 'pre') {
              url = `https://3g.crm1001.com/v2/disc/#/disc/question?personId=${personId}&iname=${personName}&phone=18825449087&from=careerPathResult&discLeftUseNum=${discLeftUseNum}&cardType=${this.info.cardType}`;
            }
            uni.navigateTo({
              url:
                '/pagesSub/public/web/descWebView?link=' +
                encodeURIComponent(url)
            });
          }
          if (
            (item.children[0].rightStatus == 2 ||
              item.children[0].rightStatus == 3) &&
            item.children[0].extra &&
            item.children[0].extra.userId
          ) {
            const userId = item.children[0].extra.userId;
            const { personName } = this.info;
            let url;
            if (env == 'test') {
              url = `https://3gtest.crm1001.com/disc/#/disc/result?userId=${userId}&personId=${personId}&iname=${personName}&phone=18825449087&from=careerPathResultt&discLeftUseNum=${discLeftUseNum}&cardType=${this.info.cardType}`;
            } else if (env == 'pro' || env == 'pre') {
              url = `https://3g.crm1001.com/v2/disc/#/disc/result?userId=${userId}&personId=${personId}&iname=${personName}&phone=18825449087&from=careerPathResultt&discLeftUseNum=${discLeftUseNum}&cardType=${this.info.cardType}`;
            }
            uni.navigateTo({
              url:
                '/pagesSub/public/web/descWebView?link=' +
                encodeURIComponent(url)
            });
          }
          if (item.children[0].rightStatus == 3 && !item.children[0].extra) {
            uni.showToast({ icon: 'none', title: '该服务已经过期!' });
          }
        }
      }
      //职途报告21是第一级，7是第二级
      if (item.rightId == 21) {
        const childItme = item.children[0];
        if (childItme.rightStatus == 1) {
          uni.showToast({ icon: 'none', title: '请咨询顾问生成职途报告！' });
        } else if (childItme.rightStatus == 2) {
          const url = childItme.extra.pdfUrl
            ? childItme.extra.pdfUrl
            : childItme.extra.pdfUrlV2;
          this.openReport(url);
        }
      }
      if (item.children.length >= 2) {
        console.log('此时进入本分支');
        item.showDesc = !item.showDesc;
        if (item.rightId === 11) {
          // 此时进入简历诊断的判断
          if (_item.rightId === 3) {
            this.reqZtBurryPoint(_item);
            uni.navigateTo({
              url: '/pagesSub/newResume/index'
            });
          }
          if (_item.rightId === 4) {
            //未使用
            if (_item.rightStatus == 1) {
              this.reqZtBurryPoint(_item);
              uni.navigateTo({
                url: '/pagesSub/AIResumeDiagnoseNew/index'
              });
              //已使用
            } else if (_item.rightStatus == 2) {
              this.reqZtBurryPoint(_item);
              uni.navigateTo({
                url: `/pagesSub/newResume/resumeAssessment/index?target=AIResumeDiagnoseNew`
              });
            }
          }
          if (_item.rightId === 15) {
            this.reqZtBurryPoint(_item);
            if (_item.extra && _item.extra.fileUrl) {
              this.openReport(_item.extra.fileUrl);
            }
          }
        }
        // AI面评
        if (item.rightId == 16 && _item.rightId == 17) {
          let array = this.mymyOrderRights;
          const targetItem = array.find((item) => item.rightId == 10);
          // if (targetItem.children[0].rightStatus == 1) {
          //   uni.showToast({ icon: "none", title: "请先完成职业测评" });
          // } else {
          let child = item.children[0];
          const queryParams = {
            userNum: child.userNum || 0,
            rightCount: child.rightCount || 3
          };
          const queryString = common.serializeQueryParams(queryParams);
          uni.navigateTo({
            url: `/pagesSub/companyCenter/interviewAI/majorSearchAI${queryString}`
          });
          // }
        }
        if (item.rightId == 16 && _item.rightId == 22) {
          this.openReport(_item.extra.fileUrl);
          // uni.navigateTo({
          //   url: _item.fileUrl,
          // });
          // }
        }
        // if (item.rightId == 16) {
        //   let array = this.mymyOrderRights;
        //   const targetItem = array.find((item) => item.rightId == 10);
        //   // if (targetItem.children[0].rightStatus == 1) {
        //   //   uni.showToast({ icon: "none", title: "请先完成职业测评" });
        //   // } else {
        //   let child = item.children[0];
        //   const queryParams = {
        //     userNum: child.userNum || 0,
        //     rightCount: child.rightCount || 3,
        //   };
        //   const queryString = common.serializeQueryParams(queryParams);
        //   uni.navigateTo({
        //     url: `/pagesSub/companyCenter/interviewAI/majorSearchAI${queryString}`,
        //   });
        //   // }
        // }
      }
    },
    //打开PDF
    openReport(fileUrl) {
      if (!fileUrl) {
        uni.showToast({ icon: 'none', title: '打开文件出错！' });
        return;
      }
      uni.showLoading({
        title: '打开中'
      });

      uni.downloadFile({
        url: fileUrl, // 文件的本身url
        filePath: wx.env.USER_DATA_PATH + '/报告' + '.pdf', // 本地自定义的文件名
        success: function (res) {
          let filePath = res.filePath;
          uni.openDocument({
            filePath: filePath,
            success: function () {
              uni.hideLoading();
            },
            fail: function () {
              uni.hideLoading();
            }
          });
          uni.hideLoading();
        },
        fail: function (res) {
          uni.hideLoading();
          uni.showToast({ icon: 'none', title: '链接已经过期！' });
        },
        complete: (res) => {
          console.log('complete', res);
        }
      });
    },
    reqZtBurryPoint(rightItem) {
      const params = {
        rightId: rightItem.rightId,
        cardType: this.info.cardType,
        personId: this.personId,
        description: `${this.personId}点击了${rightItem.rightName}`
      };
      ztBurryPoint(params)
        .then((res) => {
          if (res.code == 200) {
            console.log(`${this.personId}点击了${rightItem.rightName}`);
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    getUserInfoFn() {
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      getUserInfo({ uid: '' }).then((res) => {
        if (res.code == 200) {
          const cardVersion = res.data.cardVersion;
          this.personId = res.data.personId;
          this.userInfo.pic = res.data.photo;
          this.userInfo.personName = res.data.personName;
          this.deadline = res.data.expireTime.slice(0, 10);
          if (cardVersion == 1) {
            this.showTip = true;
          } else {
            this.info = res.data;
            this.reqGetMyRankingInfo();
            // if (res.data.consultantId) {
            //   this.getConsultantInfo(res.data.consultantId);
            // }
            // setTimeout(() => {
            //   this.checkAvatarDifference();
            // }, 2000);
          }
        }
      });
    },
    reqGetMyRankingInfo() {
      const params = {
        cardType: this.info.cardType || 6,
        personId: this.personId
      };
      getMyRankingInfo(params)
        .then((res) => {
          if (res.code == 200) {
            this.myRankInfo = res.data;
            //10没变，20上升，30下降
            if (res.data.rankingTrends == 20) {
              this.trendIcon = this.goingUp;
            } else if (res.data.rankingTrends == 30) {
              this.trendIcon = this.goingDown;
            }
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    async myOrderRights() {
      const params = { uid: '' };
      const res = await myOrderRights(params);
      if (res.code === 200) {
        console.log('res', res);
        res.data.forEach((element) => {
          if (element.rightId == 16) {
            element.children.forEach((item) => {
              // if (item.rightId == 17) {
              //   item.rightName = "测评机会，去完成";
              // }
            });
          }
        });
        this.mymyOrderRights = res.data;
      }
    },
    handleScrollToTop(e) {
      // console.log("e.detail.scrollTop", e.detail.scrollTop);
      this.currentScrollTop = e.detail.scrollTop;
    }
  }
};
</script>

<style lang="scss" scoped>
@font-face {
  font-family: 'shenshiBlack'; /*定义字体名称*/
  src: url('https://img3.job1001.com/ypMp/elan/images/career/positionDictionary/shenshiBlack.ttf');
}
$img-base-person: $img-base + 'careerPath/';
.my-rights-v2 {
  .basic-info {
    width: 100%;
    // height: 832rpx;
    height: 100vh;
    background-image: url($img-base + 'careerPath/pageBg.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    padding: 24rpx 32rpx;
    overflow-y: scroll;
    .info-card,
    .current-levle,
    .rights-logo {
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }
    .info-card {
      position: relative;
      margin-top: 12vh;
      width: 100%;
      height: 280rpx;
      // box-shadow: 3px 3px 6px rgb(0, 0, 0, 0.4);
      box-shadow: 0rpx 4rpx 14rpx 0rpx rgba(0, 0, 0, 0.05);
      background-image: url($img-base + 'careerPath/infoCardBg.png');
      .current-levle,
      .current-levle-consultant {
        position: absolute;
        left: 0;
        top: 0;
        width: 186rpx;
        height: 50rpx;
        background-size: 100% 100%;
        background-repeat: no-repeat;
      }
      .current-levle {
        background-image: url($img-base + 'careerPath/currentLevel.png');
      }
      .current-levle-consultant {
        background-image: url($img-base + 'careerPath/currentLevelConsultant.png');
      }
      .rights-logo,
      .rights-logo-consultant {
        position: absolute;
        right: -32rpx;
        top: -22rpx;
        width: 318rpx;
        height: 224rpx;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        // background-image: url($img-base + "careerPath/rightsBg.png");
      }
      .rights-logo {
        background-image: url($img-base + 'careerPath/rightsBg.png');
      }
      .rights-logo-consultant {
        background-image: url($img-base + 'careerPath/rightsBgConsultant.png');
      }
      .person-info {
        /* width: 230rpx; */
        height: 100rpx;
        position: absolute;
        top: 74rpx;
        left: 32rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        .avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 64rpx;
          border: 4rpx solid #ffffff;
          object-fit: cover;
          margin-right: 16rpx;
          flex-basis: 80rpx;
        }
        .version-name {
          flex: 1;
          display: flex;
          flex-direction: column;
          align-items: left;
          justify-content: center;
          .version {
            font-size: 40rpx;
            font-family: shenshiBlack;
            font-weight: 400;
          }
          .name {
            font-size: 28rpx;
            font-family: PingFang-SC, PingFang-SC;
            font-weight: 800;
            color: #333333;
            margin-top: 12rpx;
          }
        }
      }
      .dead-line {
        position: absolute;
        bottom: 48rpx;
        left: 36rpx;
        font-size: 24rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #acacac;
      }
    }
  }
  .rights-list {
    width: 100%;
    // height: 90vh;
    padding: 24rpx 32rpx;
    position: absolute;
    top: 516rpx;
    .rights-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      .color-title {
        width: 8rpx;
        height: 28rpx;
        border-radius: 4rpx;
      }
      .rights-name {
        font-size: 30rpx;
        font-family: PingFang-SC, PingFang-SC;
        font-weight: 800;
        color: #222222;
        margin-left: 6rpx;
      }
      .notify {
        color: #686997;
        span {
          color: #685efe;
          margin: 0 10rpx;
        }
      }
    }
    .rights-content {
      width: 100%;
      // height: 54vh;
      // height: 80vh;
      background: #ffffff;
      border-radius: 28rpx;
      margin-top: 18rpx;
      padding-bottom: 20rpx;
      .rights-item {
        width: 100%;
        padding: 32rpx 34rpx 32rpx 32rpx;
        border-bottom: 2rpx solid #e9e9e9;
        .first-line {
          width: 100%;
          font-size: 30rpx;
          font-weight: bold;
          color: #333333;
        }
        .second-line {
          margin-top: 18rpx;
          width: 100%;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          .current-type {
            font-size: 28rpx;
            font-weight: 400;
            color: #999999;
          }
          .current-step {
            font-size: 26rpx;
            font-weight: bold;
            // color: #50bc5a;
            display: flex;
            align-items: center;
            span {
              font-size: 28rpx;
              font-weight: 400;
              color: #999999;
              margin-right: 24rpx;
            }
            .no-arrow {
              width: 16rpx;
              height: 16rpx;
            }
            .green-arrow {
              width: 16rpx;
              height: 16rpx;
              background-image: url($img-base + 'careerPath/greenArrow.png');
              background-size: 100% 100%;
              background-repeat: no-repeat;
            }
          }
        }
      }
    }
    .bottom {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 32rpx;
      font-size: 24rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #bfbfbf;
    }
  }
}
</style>
